package cn.org.mrliu.ssm.service.impl;

import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import cn.org.mrliu.ssm.common.mapper.BaseMapper;
import cn.org.mrliu.ssm.common.service.impl.BaseServiceSupport;
import cn.org.mrliu.ssm.mapper.DepartmentMapper;
import cn.org.mrliu.ssm.model.Department;
import cn.org.mrliu.ssm.service.DepartmentService;

@Service
public class DepartmentServiceImpl extends BaseServiceSupport<Department> implements DepartmentService {
	@Resource
	private DepartmentMapper departmentMapper;

	@Resource
	private RedisTemplate<String, Department> redisTemplate;

	private static String departmentCacheKey = "department-";

	@SuppressWarnings("rawtypes")
	@Override
	protected BaseMapper getBaseMapper() {
		return departmentMapper;
	}

	// @CacheEvict(value="departmentCache",allEntries=true)
	@Override
	public void addDepartment(Department department) throws Exception {
		System.out.println("addDepartment.....");
		departmentMapper.save(department);
	}

	// @CacheEvict(value="departmentCache",allEntries=true)
	@Override
	public void updateDepartment(Department department) throws Exception {
		System.out.println("updateDepartment.....");
		departmentMapper.update(department);
	}

	// @CacheEvict(value="departmentCache",allEntries=true)
	@Override
	public void deleteDepartment(Integer id) throws Exception {
		System.out.println("deleteDepartment.....");
		departmentMapper.delete(id);
	}

	// @Cacheable(value="departmentCache")
	@Override
	public Department getDepartment(Integer id) throws Exception {
		System.out.println("getDepartment.....");
		String key = departmentCacheKey + id;
		String hashKey = "id:" + id;
		Department department = null;
		ValueOperations<String, Department> valueOperations = redisTemplate.opsForValue();
		department = valueOperations.get(key);
		System.out.println("------------------>>>get");
		System.out.println(department);
		System.out.println(redisTemplate.opsForHash().get("departmentHash", hashKey));
		if (department != null) {
			return department;
		}

		// 从数据库中获取部门对象
		department = departmentMapper.get(id);
		valueOperations.set(key, department);

		System.out.println("------------------>>>set");
		// 存入到hash中
		redisTemplate.opsForHash().put("departmentHash", "id:" + id, department);
		// 存入到set中
		redisTemplate.opsForSet().add("departmentSet", department);
		// 存入到list中
		redisTemplate.opsForList().leftPush("departmentList", department);

		return department;
	}

}
